<template>
  <div class="points-data">
    <el-card>
      <div class="page-header">
        <h2>积分数据看板</h2>
        <div class="header-actions">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 240px; margin-right: 12px;"
            @change="handleDateChange"
          />
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </div>
      </div>

      <!-- 核心指标卡片 -->
      <div class="metrics-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card class="metric-card">
              <div class="metric-content">
                <div class="metric-icon points-icon">
                  <el-icon><WalletFilled /></el-icon>
                </div>
                <div class="metric-info">
                  <div class="metric-value">{{ totalPoints }}</div>
                  <div class="metric-label">总积分发放量</div>
                  <div class="metric-trend">
                    <span :class="pointsTrend >= 0 ? 'trend-up' : 'trend-down'">
                      {{ pointsTrend >= 0 ? '+' : '' }}{{ pointsTrend }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="metric-card">
              <div class="metric-content">
                <div class="metric-icon users-icon">
                  <el-icon><User /></el-icon>
                </div>
                <div class="metric-info">
                  <div class="metric-value">{{ activeUsers }}</div>
                  <div class="metric-label">活跃用户数</div>
                  <div class="metric-trend">
                    <span :class="usersTrend >= 0 ? 'trend-up' : 'trend-down'">
                      {{ usersTrend >= 0 ? '+' : '' }}{{ usersTrend }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="metric-card">
              <div class="metric-content">
                <div class="metric-icon signin-icon">
                  <el-icon><Calendar /></el-icon>
                </div>
                <div class="metric-info">
                  <div class="metric-value">{{ signinRate }}%</div>
                  <div class="metric-label">签到率</div>
                  <div class="metric-trend">
                    <span :class="signinTrend >= 0 ? 'trend-up' : 'trend-down'">
                      {{ signinTrend >= 0 ? '+' : '' }}{{ signinTrend }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card class="metric-card">
              <div class="metric-content">
                <div class="metric-icon exchange-icon">
                  <el-icon><GoodsFilled /></el-icon>
                </div>
                <div class="metric-info">
                  <div class="metric-value">{{ exchangeRate }}%</div>
                  <div class="metric-label">积分兑换率</div>
                  <div class="metric-trend">
                    <span :class="exchangeTrend >= 0 ? 'trend-up' : 'trend-down'">
                      {{ exchangeTrend >= 0 ? '+' : '' }}{{ exchangeTrend }}%
                    </span>
                    较上期
                  </div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表区域 -->
      <div class="charts-section">
        <el-row :gutter="20">
          <!-- 积分获取与消耗趋势 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>积分获取与消耗趋势</span>
                  <el-radio-group v-model="trendPeriod" size="small">
                    <el-radio-button label="7d">7天</el-radio-button>
                    <el-radio-button label="30d">30天</el-radio-button>
                    <el-radio-button label="90d">90天</el-radio-button>
                  </el-radio-group>
                </div>
              </template>
              <div class="chart-container" ref="trendChartRef"></div>
            </el-card>
          </el-col>

          <!-- 积分来源分布 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>积分来源分布</span>
                </div>
              </template>
              <div class="chart-container" ref="sourceChartRef"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <!-- 签到行为分析 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>签到行为分析</span>
                </div>
              </template>
              <div class="chart-container" ref="signinChartRef"></div>
            </el-card>
          </el-col>

          <!-- 用户积分余额分布 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>用户积分余额分布</span>
                </div>
              </template>
              <div class="chart-container" ref="balanceChartRef"></div>
            </el-card>
          </el-col>
        </el-row>

        <el-row :gutter="20" style="margin-top: 20px;">
          <!-- 积分兑换商品排行 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>积分兑换商品排行</span>
                </div>
              </template>
              <div class="chart-container" ref="goodsChartRef"></div>
            </el-card>
          </el-col>

          <!-- 用户等级积分使用分析 -->
          <el-col :span="12">
            <el-card class="chart-card">
              <template #header>
                <div class="card-header">
                  <span>用户等级积分使用分析</span>
                </div>
              </template>
              <div class="chart-container" ref="levelChartRef"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 明细与分析区块 -->
      <div class="analysis-section">
        <el-row :gutter="20">
          <!-- 积分明细表 -->
          <el-col :span="24">
            <el-card class="analysis-card">
              <template #header>
                <div class="card-header">
                  <span>积分明细表</span>
                  <el-button size="small" @click="exportTable">导出Excel</el-button>
                </div>
              </template>
              <el-table :data="pointsTableData" style="width:100%;margin-bottom:12px;">
                <el-table-column prop="user" label="用户" min-width="120" />
                <el-table-column prop="type" label="类型" width="80" />
                <el-table-column prop="amount" label="积分变动" width="100" />
                <el-table-column prop="source" label="来源/去向" width="120" />
                <el-table-column prop="date" label="时间" width="140" />
                <el-table-column prop="status" label="状态" width="80" />
              </el-table>
              <el-pagination
                v-model:current-page="tablePage.current"
                :page-size="tablePage.size"
                :total="pointsTableData.length"
                layout="prev, pager, next"
                style="margin-top:8px; text-align:right;" />
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top:20px;">
          <!-- 用户积分排行 -->
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header><span>用户积分排行</span></template>
              <el-table :data="userRankData" size="small" style="width:100%;">
                <el-table-column prop="rank" label="排名" width="60" />
                <el-table-column prop="user" label="用户" min-width="100" />
                <el-table-column prop="points" label="积分" width="100" />
              </el-table>
            </el-card>
          </el-col>
          <!-- 消耗渠道分布 -->
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header><span>消耗渠道分布</span></template>
              <div class="chart-container" ref="channelChartRef" style="height:220px;"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top:20px;">
          <!-- 过期积分统计 -->
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header><span>过期积分统计</span></template>
              <div class="chart-container" ref="expireChartRef" style="height:220px;"></div>
            </el-card>
          </el-col>
          <!-- 活动效果分析 -->
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header><span>活动效果分析</span></template>
              <div class="chart-container" ref="activityChartRef" style="height:220px;"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top:20px;">
          <!-- 订单关联分析 -->
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header><span>订单关联分析</span></template>
              <div class="chart-container" ref="orderChartRef" style="height:220px;"></div>
            </el-card>
          </el-col>
          <!-- 积分流失分析 -->
          <el-col :span="12">
            <el-card class="analysis-card">
              <template #header><span>积分流失分析</span></template>
              <div class="chart-container" ref="lossChartRef" style="height:220px;"></div>
            </el-card>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top:20px;">
          <!-- 时间对比分析 -->
          <el-col :span="24">
            <el-card class="analysis-card">
              <template #header><span>自定义时间周期对比</span></template>
              <div class="compare-bar">
                <el-date-picker v-model="compareRange1" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width:220px;margin-right:8px;" />
                <el-date-picker v-model="compareRange2" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" style="width:220px;" />
                <el-button type="primary" size="small" @click="compareData">对比</el-button>
              </div>
              <div class="chart-container" ref="compareChartRef" style="height:220px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { WalletFilled, User, Calendar, GoodsFilled } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 日期范围
const dateRange = ref([])

// 核心指标数据
const totalPoints = ref(1256800)
const pointsTrend = ref(12.5)
const activeUsers = ref(8560)
const usersTrend = ref(8.3)
const signinRate = ref(78.5)
const signinTrend = ref(-2.1)
const exchangeRate = ref(45.2)
const exchangeTrend = ref(15.7)

// 图表周期
const trendPeriod = ref('30d')

// 图表引用
const trendChartRef = ref()
const sourceChartRef = ref()
const signinChartRef = ref()
const balanceChartRef = ref()
const goodsChartRef = ref()
const levelChartRef = ref()

// 图表实例
let trendChart: echarts.ECharts
let sourceChart: echarts.ECharts
let signinChart: echarts.ECharts
let balanceChart: echarts.ECharts
let goodsChart: echarts.ECharts
let levelChart: echarts.ECharts

// 初始化积分获取与消耗趋势图
function initTrendChart() {
  if (!trendChartRef.value) return
  
  trendChart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['积分获取', '积分消耗', '积分余额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '积分获取',
        type: 'line',
        smooth: true,
        data: [12000, 15000, 18000, 22000, 25000, 28000, 32000],
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '积分消耗',
        type: 'line',
        smooth: true,
        data: [8000, 12000, 15000, 18000, 20000, 22000, 25000],
        itemStyle: { color: '#F56C6C' }
      },
      {
        name: '积分余额',
        type: 'line',
        smooth: true,
        data: [4000, 3000, 3000, 4000, 5000, 6000, 7000],
        itemStyle: { color: '#409EFF' }
      }
    ]
  }
  
  trendChart.setOption(option)
}

// 初始化积分来源分布图
function initSourceChart() {
  if (!sourceChartRef.value) return
  
  sourceChart = echarts.init(sourceChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left'
    },
    series: [
      {
        name: '积分来源',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 45, name: '签到', itemStyle: { color: '#67C23A' } },
          { value: 25, name: '购物', itemStyle: { color: '#409EFF' } },
          { value: 15, name: '活动', itemStyle: { color: '#E6A23C' } },
          { value: 10, name: '任务', itemStyle: { color: '#F56C6C' } },
          { value: 5, name: '其他', itemStyle: { color: '#909399' } }
        ]
      }
    ]
  }
  
  sourceChart.setOption(option)
}

// 初始化签到行为分析图
function initSigninChart() {
  if (!signinChartRef.value) return
  
  signinChart = echarts.init(signinChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['签到人数', '连续签到']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '签到人数',
        type: 'bar',
        data: [1200, 1350, 1400, 1380, 1450, 1600, 1800],
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '连续签到',
        type: 'bar',
        data: [800, 950, 1100, 1050, 1200, 1300, 1500],
        itemStyle: { color: '#67C23A' }
      }
    ]
  }
  
  signinChart.setOption(option)
}

// 初始化用户积分余额分布图
function initBalanceChart() {
  if (!balanceChartRef.value) return
  
  balanceChart = echarts.init(balanceChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    series: [
      {
        name: '积分余额',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 45, name: '0-100', itemStyle: { color: '#F56C6C' } },
          { value: 25, name: '101-500', itemStyle: { color: '#E6A23C' } },
          { value: 15, name: '501-1000', itemStyle: { color: '#409EFF' } },
          { value: 10, name: '1001-5000', itemStyle: { color: '#67C23A' } },
          { value: 5, name: '5000+', itemStyle: { color: '#909399' } }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  balanceChart.setOption(option)
}

// 初始化积分兑换商品排行图
function initGoodsChart() {
  if (!goodsChartRef.value) return
  
  goodsChart = echarts.init(goodsChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value'
    },
    yAxis: {
      type: 'category',
      data: ['商品A', '商品B', '商品C', '商品D', '商品E']
    },
    series: [
      {
        name: '兑换次数',
        type: 'bar',
        data: [320, 280, 250, 220, 180],
        itemStyle: { color: '#409EFF' }
      }
    ]
  }
  
  goodsChart.setOption(option)
}

// 初始化用户等级积分使用分析图
function initLevelChart() {
  if (!levelChartRef.value) return
  
  levelChart = echarts.init(levelChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['获取积分', '使用积分', '积分余额']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['普通用户', 'VIP用户', '高级用户']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '获取积分',
        type: 'bar',
        data: [1200, 2500, 3800],
        itemStyle: { color: '#67C23A' }
      },
      {
        name: '使用积分',
        type: 'bar',
        data: [800, 1800, 2800],
        itemStyle: { color: '#F56C6C' }
      },
      {
        name: '积分余额',
        type: 'bar',
        data: [400, 700, 1000],
        itemStyle: { color: '#409EFF' }
      }
    ]
  }
  
  levelChart.setOption(option)
}

// 处理日期变化
function handleDateChange() {
  refreshData()
}

// 刷新数据
function refreshData() {
  ElMessage.success('数据已刷新')
  // 这里可以调用API重新获取数据
}

// 监听窗口大小变化
function handleResize() {
  trendChart?.resize()
  sourceChart?.resize()
  signinChart?.resize()
  balanceChart?.resize()
  goodsChart?.resize()
  levelChart?.resize()
}

// 明细表mock
const pointsTableData = ref([
  { user: '张三', type: '签到', amount: '+10', source: '每日签到', date: '2024-07-01 09:00', status: '已入账' },
  { user: '李四', type: '下单', amount: '+50', source: '订单#20240101', date: '2024-07-01 10:00', status: '已入账' },
  { user: '王五', type: '兑换', amount: '-100', source: '兑换商品', date: '2024-07-01 11:00', status: '已消耗' },
  { user: '赵六', type: '活动', amount: '+30', source: '618活动', date: '2024-07-01 12:00', status: '已入账' },
  { user: '张三', type: '过期', amount: '-20', source: '过期作废', date: '2024-07-01 13:00', status: '已过期' }
])
const tablePage = ref({ current: 1, size: 10 })
function exportTable() {
  ElMessage.success('导出成功（mock）')
}
// 用户积分排行mock
const userRankData = ref([
  { rank: 1, user: '张三', points: 1200 },
  { rank: 2, user: '李四', points: 1100 },
  { rank: 3, user: '王五', points: 900 },
  { rank: 4, user: '赵六', points: 800 },
  { rank: 5, user: '钱七', points: 700 }
])
// 分析图表ref
const channelChartRef = ref(), expireChartRef = ref(), activityChartRef = ref(), orderChartRef = ref(), lossChartRef = ref(), compareChartRef = ref()
const compareRange1 = ref([]), compareRange2 = ref([])
function compareData() {
  ElMessage.success('对比分析已生成（mock）')
}
// 图表初始化（mock数据）
onMounted(() => {
  nextTick(() => {
    initTrendChart()
    initSourceChart()
    initSigninChart()
    initBalanceChart()
    initGoodsChart()
    initLevelChart()
    
    window.addEventListener('resize', handleResize)
  })
  // 消耗渠道分布
  if (channelChartRef.value) {
    const chart = echarts.init(channelChartRef.value)
    chart.setOption({
      title: { text: '消耗渠道', left: 'center', top: 10, textStyle: { fontSize: 14 } },
      tooltip: { trigger: 'item' },
      legend: { bottom: 0 },
      series: [{ type: 'pie', radius: '60%', data: [ { value: 300, name: '兑换商品' }, { value: 200, name: '订单抵扣' }, { value: 100, name: '抽奖' } ] }]
    })
  }
  if (expireChartRef.value) {
    const chart = echarts.init(expireChartRef.value)
    chart.setOption({
      title: { text: '过期积分', left: 'center', top: 10, textStyle: { fontSize: 14 } },
      tooltip: { trigger: 'item' },
      legend: { bottom: 0 },
      series: [{ type: 'pie', radius: '60%', data: [ { value: 500, name: '过期' }, { value: 100, name: '作废' } ] }]
    })
  }
  if (activityChartRef.value) {
    const chart = echarts.init(activityChartRef.value)
    chart.setOption({
      title: { text: '活动效果', left: 'center', top: 10, textStyle: { fontSize: 14 } },
      tooltip: { trigger: 'item' },
      legend: { bottom: 0 },
      series: [{ type: 'pie', radius: '60%', data: [ { value: 200, name: '签到活动' }, { value: 150, name: '下单返积分' }, { value: 100, name: '积分抽奖' } ] }]
    })
  }
  if (orderChartRef.value) {
    const chart = echarts.init(orderChartRef.value)
    chart.setOption({
      title: { text: '订单关联分析', left: 'center', top: 10, textStyle: { fontSize: 14 } },
      tooltip: { trigger: 'axis' },
      legend: { bottom: 0, data: ['订单数', '积分消耗'] },
      xAxis: { type: 'category', data: ['1-10', '11-20', '21-30', '31-40', '41-50'] },
      yAxis: { type: 'value' },
      series: [
        { name: '订单数', type: 'bar', data: [120, 132, 101, 134, 90] },
        { name: '积分消耗', type: 'line', data: [500, 600, 550, 700, 650] }
      ]
    })
  }
  if (lossChartRef.value) {
    const chart = echarts.init(lossChartRef.value)
    chart.setOption({
      title: { text: '积分流失', left: 'center', top: 10, textStyle: { fontSize: 14 } },
      tooltip: { trigger: 'item' },
      legend: { bottom: 0 },
      series: [{ type: 'pie', radius: '60%', data: [ { value: 300, name: '未活跃用户积分' }, { value: 200, name: '过期积分' } ] }]
    })
  }
  if (compareChartRef.value) {
    const chart = echarts.init(compareChartRef.value)
    chart.setOption({
      title: { text: '自定义时间对比', left: 'center', top: 10, textStyle: { fontSize: 14 } },
      tooltip: { trigger: 'axis' },
      legend: { bottom: 0, data: ['周期1', '周期2'] },
      xAxis: { type: 'category', data: ['1', '2', '3', '4', '5', '6', '7'] },
      yAxis: { type: 'value' },
      series: [
        { name: '周期1', type: 'line', data: [100, 120, 110, 130, 125, 140, 135] },
        { name: '周期2', type: 'line', data: [90, 110, 105, 120, 115, 130, 125] }
      ]
    })
  }
})
</script>

<style scoped>
.points-data {
  padding: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.metrics-cards {
  margin-bottom: 24px;
}

.metric-card {
  height: 120px;
}

.metric-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.metric-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.points-icon {
  background: linear-gradient(135deg, #67C23A, #85CE61);
}

.users-icon {
  background: linear-gradient(135deg, #409EFF, #66B1FF);
}

.signin-icon {
  background: linear-gradient(135deg, #E6A23C, #EEBE77);
}

.exchange-icon {
  background: linear-gradient(135deg, #F56C6C, #F78989);
}

.metric-info {
  flex: 1;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.metric-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.metric-trend {
  font-size: 12px;
  color: #909399;
}

.trend-up {
  color: #67C23A;
  font-weight: bold;
}

.trend-down {
  color: #F56C6C;
  font-weight: bold;
}

.charts-section {
  margin-top: 24px;
}

.chart-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  width: 100%;
}
.analysis-section {
  margin-top: 24px;
}
.analysis-card {
  margin-bottom: 20px;
}
.compare-bar {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
</style> 